package cn.collin.commons.web.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.taglibs.standard.tag.el.core.ExpressionUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import cn.collin.commons.web.filter.OpenSessionInViewHibernateFilter;

/**
 * execute query hql
 * 
 * http://collincode.googlecode.com
 * 
 * @author collin.code@gmail.com
 * 
 */
public class HQueryTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	String var;

	String hql;

	String hql_el;

	public void setHql(String hql) {
		this.hql_el = hql;
	}

	public void setVar(String var) {
		this.var = var;
	}

	@Override
	public int doStartTag() throws JspException {
		hql = (String) ExpressionUtil.evalNotNull("hquery", "hql", hql_el,
				String.class, this, pageContext);
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		Session session = (Session) TransactionSynchronizationManager
				.getResource(OpenSessionInViewHibernateFilter.SESSION_NAME);
		Query query = session.createQuery(hql);
		pageContext.setAttribute(var, query.list(), PageContext.PAGE_SCOPE);
		return EVAL_PAGE;
	}

}
